package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    private IRoleService roleService;

    @Autowired
    public void setRoleService(IRoleService roleService) {
        this.roleService = roleService;
    }
    @Autowired
    private IPermissionService permissionService;
    //处理查询所有角色的请求,响应HTML
    //role/*.do
    @RequiredPermission(name = "角色页面", expression = "role:list")
    @RequestMapping("/list")
    public String list(Model model, QueryObject qo) {
        System.out.println(qo);
        PageInfo<Role> query = roleService.query(qo);
        model.addAttribute("pageInfo", query);
        return "role/list";// 找视图 /WEB-INF/views/role/list.jsp
    }

    //处理删除请求
    //  role/delete.dp?id=1,  重定向到  /role/list.do
    @RequiredPermission(name = "角色删除", expression = "role:delete")
    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
            roleService.delete(id);
        }
        //让浏览器重新发送一次请求
        return "redirect:/role/list";
    }

    //去新增或者去修改页面
    @RequiredPermission(name = "角色新增/修改", expression = "role:saveOrUpdate")
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        List<Permission> permissions = permissionService.listAll();
        model.addAttribute("permissions",permissions);



        if (id != null) {//表示去修改
            Role role = roleService.get(id);
            model.addAttribute("role", role);

            List<Permission> permissionsByRid = permissionService.selectByRid(id);
            model.addAttribute("permissionsByRid",permissionsByRid);
        }
        return "role/input";//让浏览器重新发一次请求
    }

    //新增或者修改
    @RequiredPermission(name = "角色新增/修改", expression = "role:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] ids) {
        if (role.getId() == null) {
            //新增
            roleService.save(role,ids);
        } else {
            //修改
            roleService.update(role,ids);
        }
        return "redirect:/role/list";//让浏览器重新发送一次请求
    }

}


